#include <sys/mman.h>  // mmap, munmap
#include <unistd.h>    // usleep
#include <cstdlib>     // rand()和srand()
#include <ctime>       // time()
#include <iostream>
#include <string>
#include <vector>

int main() {
  // alloc different type of memory
  {
    const int* intPtr = new int[100];
    std::cout << "Allocated int array at: " << intPtr << std::endl;
  }

  {
    const double* doublePtr = new double(3.14);
    std::cout << "Allocated double at: " << doublePtr << ", value: " << *doublePtr << std::endl;
  }

  {
    const std::string* strPtr = new std::string("Hello, World!");
    std::cout << "Allocated string at: " << strPtr << ", value: " << *strPtr << std::endl;
  }

  {
    // alloc dynamic array
    size_t arraySize = 10;
    size_t* const arrayPtr = new size_t[arraySize];
    std::cout << "Allocated array of " << arraySize << " ints at: " << arrayPtr << std::endl;
    for (size_t i = 0; i < arraySize; ++i) {
      arrayPtr[i] = i;
    }
  }

  {
    // use mmap to allocate memory
    size_t mmapSize = 4096;  // 4KB
    const void* mmapPtr = mmap(nullptr, mmapSize, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
    if (mmapPtr == MAP_FAILED) {
      perror("mmap failed");
    } else {
      std::cout << "Allocated mmap at: " << mmapPtr << ", size: " << mmapSize << " bytes" << std::endl;
    }
  }

  while (true) {
    usleep(100000);  // 100ms
  }

  return 0;
}
